package com.files.model;

import lombok.Data;
import lombok.ToString;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Data
@ToString
public class FileInfo {

    /**
     * 文件名称
     */
    private String originalFilename;
    /**
     * 文件名称
     */
    private String name;
    /**
     * 文件类型
     */
    private String mimeType;
    /**
     * 文件目录
     */
    private String catalog;
    /**
     * 文件URL
     */
    private String url;
    /**
     * 文件bytes
     */
    private byte[] bytes;
    /**
     * 文件
     */
    private File file;
    /**
     * 文件输入流
     */
    private InputStream inputStream;
    /**
     * 文件元数据
     */
    private Map<String, Object> metadata = new HashMap<String, Object>();
    /**
     * 文件大小
     */
    private long size;


    public Boolean isEmpty() {
        return null == file && null == inputStream && null == bytes;
    }

    public byte[] getBytes() {
        if (null != bytes) {
            return bytes;
        }
        if (null != inputStream) {
            try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) {
                //buff用于存放循环读取的临时数据
                byte[] buff = new byte[1024];
                int rc = 0;
                while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                byte[] byteArray = swapStream.toByteArray();
                return byteArray;
            } catch (Exception e) {
                throw new RuntimeException("cast bytes exception");
            }
        }
        return null;
    }

    public InputStream getInputStream() {
        if (null != inputStream) {
            return inputStream;
        }
        if (file != null) {
            try (InputStream inputStream = new FileInputStream(file)) {
                return inputStream;
            } catch (Exception e) {
                throw new RuntimeException("cast inputStream exception");
            }
        }
        return null;
    }


}
